<template>
  <el-form>
    <el-row>
      <el-col :span="24">
        <el-form-item prop="message" label="提示" :label-width="labelWidth">
          <el-input v-model="formData.message" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="trigger" label="事件" :label-width="labelWidth">
          <el-input v-model="formData.trigger" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="type" label="类型" :label-width="labelWidth">
          <el-select v-model="formData.type">
            <el-option
              v-for="item in validatorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="required" label="必填" :label-width="labelWidth">
          <el-switch v-model="formData.required" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="min" label="min" :label-width="labelWidth">
          <el-input v-model="formData.min" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="max" label="max" :label-width="labelWidth">
          <el-input v-model="formData.max" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="pattern" label="pattern" :label-width="labelWidth">
          <el-input v-model="formData.pattern" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="len" label="len" :label-width="labelWidth">
          <el-input v-model="formData.len" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import _ from "lodash";
import { ValidatorOptions } from "../../basic";
export default {
  name: "RuleAttributeEditor",
  props: ["value"],
  data() {
    return {
      formData: {},
      unwatch: null,
      labelWidth: "75px",
      validatorOptions: new ValidatorOptions()
    };
  },
  created() {
    this.createData();
    this.createWatch();
  },
  beforeDestroy() {
    this.removeWatch();
  },
  methods: {
    createData() {
      this.formData = _.cloneDeep(this.value || {});
    },
    createWatch() {
      this.unwatch = this.$watch(
        "formData",
        (data) => {
          this.$emit("input", data);
        },
        { deep: true }
      );
    },
    removeWatch() {
      if (this.unwatch) {
        this.unwatch();
        this.unwatch = null;
      }
    }
  },
  watch: {
    value() {
      this.removeWatch();
      this.createData();
      this.createWatch();
    }
  }
};
</script>
